<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <ul id="list"></ul>
    <input type="text" id="message">
    <button type="button" id="sendBtn">发送</button>
    <p>uuid:
        <spand id="uuid">
        </spand>
    </p>
    <script>
        const host = 'ws://localhost:3000/ws'
        const inputMessage = document.querySelector( '#message' )
        const ulList = document.querySelector( '#list' )
        const btnSend = document.querySelector( '#sendBtn' )

        const ws = new WebSocket(host);
        ws.onopen = (res) => {
            console.log(res);
            console.log("来自客户端");
        }

        ws.onmessage = (res) => {
            console.log(res);
            console.log("来自服务端");
            const data = JSON.parse(res.data);
            console.log(data);
            if(data.context === 'user'){
                document.getElementById('uuid').innerHTML = data.uuid;
            }else if(data.context === 'message'){
                const li = document.createElement('li');
                li.innerHTML = data.content;
                ulList.appendChild(li);
            }
        }

        btnSend.onclick = () => {
            console.log('点击了发送按钮');
            const content = inputMessage.value;
            ws.send(JSON.stringify({
                context: 'message',
                uuid: document.getElementById('uuid').innerHTML,
                content
            }));
        }
    </script>
</body>
</html>